<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/11/2
 * Time: 14:46
 */

namespace app\api\model;


class CardTag extends BaseModel
{
    protected $hidden=['w_id','create_time','delete_time','update_time'];
    protected $autoWriteTimestamp = true;

    /**
     * 自定义标签点击
     * @param $id
     * @return int|true
     */
    public function clickTag($id){
        $user = self::get($id);
        $user->setInc('click');
        return $user->click;
    }

    /**
     * 获取标签列表
     * @param $w_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getTagList($w_id){
        $list = self::where('w_id','=',$w_id)->select();
        return $list;
    }

    /**
     * 获取用户标签
     * @param $wu_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getTag($wu_id){
        $tag = self::where('w_id','=',$wu_id)->select();
        return $tag;
    }

    /**
     * 添加标签
     * @param $info
     * @param $wu_id
     * @return array|false
     */
    public static function addTag($info,$wu_id){
        foreach ($info as $key=>$value){
            $data[$key]['name'] = $value;
            $data[$key]['w_id'] = $wu_id;
        }
        return (new CardTag())->saveAll($data);
    }

    /**
     * 更新标签
     * @param $info
     * @param $wu_id
     * @return array|false
     */
    public static function updateTag($info,$wu_id){
        $tags = self::where('w_id','=',$wu_id)
                ->field('name')->select();
        foreach ($tags as $value){
            $tag[] = $value['name'];
        }
        $data = array_intersect($info,$tag);//交集
        if (empty($data)){
            self::where('w_id','=',$wu_id)->delete();
               foreach ($info as $key=>$value){
                    $add[$key]['name'] = $value;
                    $add[$key]['w_id'] = $wu_id;
                }
                $result = (new CardTag())->saveAll($add);
        }else{
            $had_data = array_diff($tag,$data);
            if (!empty($had_data)) {
                self::where('w_id', '=', $wu_id)->where('name', 'in', $had_data)->delete();//删除原有
            }
                $new_fata = array_diff($info, $data);
                if ($new_fata != null){
                    foreach ($new_fata as $key => $value) {
                        $add[$key]['name'] = $value;
                        $add[$key]['w_id'] = $wu_id;
                    }
                    $result = (new CardTag())->saveAll($add);//添加新增
                }else{
                    $result = 'success';
                }
        }
    return $result;
    }
}